package kz.pompei.ifacer.grot;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.UUID;

import kz.pompei.ifacer.model.widgets.Widget;

public class ReaderUtil {
  
  private static void setFieldInner(Widget widget, String name, String value) throws Exception {
    Field field = widget.getClass().getField(name);
    field.set(widget, convert(value, field.getType()));
  }
  
  public static Object convert(String strValue, Class<?> toType) throws Exception {
    if (strValue == null) return null;
    
    if (toType.isEnum()) {
      Method m = toType.getMethod("valueOf", String.class);
      return m.invoke(toType, strValue);
    }
    
    if (String.class.equals(toType)) return strValue;
    if (Integer.class.equals(toType)) return Integer.valueOf(strValue);
    if (Integer.TYPE.equals(toType)) return Integer.valueOf(strValue);
    if (Boolean.class.equals(toType)) return Boolean.valueOf(strValue);
    if (Boolean.TYPE.equals(toType)) return Boolean.valueOf(strValue);
    
    throw new IllegalArgumentException("Cannot convert to type " + toType + " the value "
        + strValue);
  }
  
  public static void setField(Widget widget, String name, String value) {
    try {
      setFieldInner(widget, name, value);
    } catch (NoSuchFieldException e) {
      //do nothing
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  
  private static Widget createWidgetInner(String type, String uuid) throws Exception {
    String clas = "kz.pompei.ifacer.model.widgets." + type;
    @SuppressWarnings("unchecked")
    Constructor<Widget> constructor = ((Class<Widget>)Class.forName(clas))
        .getConstructor(UUID.class);
    return constructor.newInstance(UUID.fromString(uuid));
  }
  
  public static Widget createWidget(String type, String uuid) {
    try {
      return createWidgetInner(type, uuid);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  
}
